let selectable = false;

function copySelectedText() {
  const selectedText = window.getSelection().toString();
  if (selectedText) {
    navigator.clipboard.writeText(selectedText).then(() => {
      console.log('Text copied to clipboard: ', selectedText);
      window.getSelection().removeAllRanges(); // 取消选中
      message('复制成功');
    }).catch(err => {
      console.error('Failed to copy text: ', err);
    });
  }
}

function message(messageText) {
  // 创建消息框元素
  const messageBox = document.createElement('div');
  messageBox.textContent = messageText;
  messageBox.className = 'message fadeInOut '; // 添加动画类
  
  // 将消息框添加到页面中
  document.body.appendChild(messageBox);
  
  // 5秒后删掉元素
  setTimeout(() => {
    messageBox.remove();
  }, 5000);
}

function enableTextSelection() {
  const css = `
    * {
      -moz-user-select: text !important;
      -webkit-user-select: text !important;
      -ms-user-select: text !important;
      -khtml-user-select: text !important;
      user-select: text !important;
    }
    .message{
      position: fixed;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 9999;
      background-color: #fff;
      text-align: center;
      padding: 10px 24px;
      border: 1px solid #EBEEF5;
      box-shadow: 0 2px 8px rgba(26, 26, 26, .1);
      opacity: 0;
      font-size: 12px;
      min-width: 100px;
    }

    @keyframes fadeInOut {
      0% {
        opacity: 0;
      }
      30% {
        opacity: 1;
      }
      80% {
        opacity: 1;
      }
      100% {
        opacity: 0;
      }
    }

    .fadeInOut {
      animation: fadeInOut 2s ease-in-out;
    }
  `;
  const style = document.createElement('style');
  style.id = 'text-selection-style';
  style.textContent = css;
  document.head.appendChild(style);
}

function disableTextSelection() {
  const style = document.getElementById('text-selection-style');
  if (style) {
    style.remove();
  }
}

function toggleSelectable() {
  selectable = !selectable;

  if (selectable) {
    enableTextSelection();
    document.addEventListener('mouseup', copySelectedText);
  } else {
    disableTextSelection();
    document.removeEventListener('mouseup', copySelectedText);
  }
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  switch (request.command) {
    case "toggleSelectable":
      toggleSelectable();
      break;
    case "getStatus":
      break;
  }
  sendResponse({status: selectable});
});
